using System.Linq;
using Magiq.Behaviors;
using Magiq.Insert;

namespace Magiq.Objects
{
    public class InsertStrategy<TSource, TDestination, TNew> : BehaviorHandler<IObjectsInsertBehavior>, IInsertStrategy
        where TDestination : class
        where TNew : class, TDestination, new()
    {
        public InsertStrategy(IInsert<TSource, TDestination, TNew> insert) : base(insert.Behavior)
        {
            this.insert = insert;
            Default<DefaultObjectsBehavior>();
        }

        public int Execute()
        {
            var destination = Call(x => x.GetInsertDestination(insert));

            var @new = insert.NewExpression.Compile();
            var items = insert.Source.ToArray();
            destination.Insert(items.Select(@new));
            return items.Length;
        }

        private readonly IInsert<TSource, TDestination, TNew> insert;
    }
}